<script setup lang="ts">
import {computed, ref, watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {renderIcon} from "@/utils/xicons.ts";
import {useUserStore} from "@/stores/user.store.ts";
import type {Component} from "vue";


interface MenuOption {
    label: string
    key: string
    icon?: Component
    children?: MenuOption[]
}


const userStore = useUserStore();
console.log("menus", userStore.userMenus);


const props = withDefaults(defineProps<{ collapsed: boolean; }>(), {
    collapsed: false,
})


const route = useRoute();
const router = useRouter();


// 菜单相关
const activeKey = ref<string>("");
const sidebarMenuOptions = ref<MenuOption[]>([
    {
        label: "仪表盘",
        key: "/dashboard",
        icon: () => renderIcon("Dashboard")
    },
    {
        label: "系统管理",
        key: "/system",
        icon: () => renderIcon("Settings"),
        children: [
            {
                label: "用户管理",
                key: "/system/user",
                icon: () => renderIcon("Users")
            },
            {
                label: "角色管理",
                key: "/system/role",
                icon: () => renderIcon("ShieldCheck")
            },
            {
                label: "菜单管理",
                key: "/system/menu",
                icon: () => renderIcon("LayoutGrid")
            }
        ]
    }
]);

const asyncSideBarMenu = computed(() => {
    const transformMenu = (menus: any[]): MenuOption[] => {
        return menus
            .filter(menu => menu.type !== 3 && menu.is_display)
            .map(menu => {
                // 预处理子菜单：过滤按钮类型并保持树结构
                const validChildren = menu.children
                        ?.filter((child: any) => child.type !== 3 && child.is_display)
                    || []

                return {
                    label: menu.name,
                    key: menu.url,
                    icon: menu.icon ? () => renderIcon(menu.icon) : undefined,
                    // 递归处理已过滤的子菜单
                    children: validChildren.length
                        ? transformMenu(validChildren)
                        : undefined,
                }
            })
    }

    // 返回转换后的菜单数据
    return transformMenu(userStore.userMenus as any[]);
});


console.log("asyncMenu", asyncSideBarMenu);


/**
 * 切换菜单
 * @param path
 */
const handleMenuSelect = (path: string) => {
    router.push(path);
};


/**
 * 动态监听路由
 */
watch(() => route.path, (path: string) => {
    activeKey.value = path;
}, {immediate: true});
</script>

<template>
    <div class="sidebar-menu">
        <n-menu
            v-model:value="activeKey"
            :options="asyncSideBarMenu"
            :key="activeKey"
            :indent="20"
            :collapsed="props.collapsed"
            :collapsed-width="64"
            @update:value="handleMenuSelect"
        />
    </div>
</template>

<style lang="scss">

</style>